package com.chatplus.application.processor.channel.chat;

import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.domain.dto.ChatConfigDto;
import com.chatplus.application.domain.entity.chat.ChatHistoryEntity;
import com.chatplus.application.domain.entity.chat.ChatItemEntity;
import com.chatplus.application.processor.handler.ChatAiSocketHandler;
import com.chatplus.application.processor.handler.dto.ChatRecordMessage;
import com.chatplus.application.service.basedata.ConfigService;
import com.chatplus.application.service.chat.ChatHistoryService;
import com.chatplus.application.service.chat.ChatItemService;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.WebSocketSession;

import java.util.List;

/**
 * Chat 类型 AI 处理器服务接口
 */
public abstract class IChatAiProcessorService {
    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(IChatAiProcessorService.class);

    private ChatItemService chatItemService;
    private ChatHistoryService chatHistoryService;
    private ConfigService configService;
    private WebSocketSession session;

    public void setSession(WebSocketSession session) {
        this.session = session;
    }

    public WebSocketSession getSession() {
        return session;
    }

    @Autowired
    public void setChatItemsService(ChatItemService chatItemService) {
        this.chatItemService = chatItemService;
    }

    @Autowired
    public void setChatHistoryService(ChatHistoryService chatHistoryService) {
        this.chatHistoryService = chatHistoryService;
    }

    @Autowired
    public void setConfigsService(ConfigService configService) {
        this.configService = configService;
    }

    public abstract void process(List<ChatRecordMessage> messageContext) throws JsonProcessingException;

    /**
     * AI 渠道处理器
     */
    public abstract String getChannel();

    // 保存聊天记录
    public void saveChatItemRecord(String prompt) {
        String chatId = session.getAttributes().get("chat_id").toString();
        Long userId = session.getAttributes().get("userId") == null ? null :
                Long.valueOf(session.getAttributes().get("userId").toString());
        // 先检查看是否已有记录，有就不存了
        ChatItemEntity chatItemEntity = chatItemService.getChatItemByChatId(chatId);
        if (chatItemEntity != null) {
            return;
        }
        chatItemEntity = new ChatItemEntity();
        chatItemEntity.setChatId(chatId);
        chatItemEntity.setModelId(Long.valueOf((String) session.getAttributes().get("model_id")));
        chatItemEntity.setRoleId(Long.valueOf((String) session.getAttributes().get("role_id")));
        chatItemEntity.setUserId(userId);
        if (prompt.length() > 30) {
            chatItemEntity.setTitle(prompt.substring(0, 30) + "...");
        } else {
            chatItemEntity.setTitle(prompt);
        }
        chatItemService.save(chatItemEntity);
    }

    /**
     * 保存聊天记录
     *
     * @param type    prompt or reply
     * @param tokens  tokens
     * @param content content
     */
    public void saveChatHistory(Long itemId,String type, Integer tokens, String content) {
        ChatConfigDto adminConfigDto = configService.getChatConfig();
        if (adminConfigDto != null && adminConfigDto.isEnableHistory()) {
            Long userId = session.getAttributes().get("userId") == null ? null :
                    Long.valueOf(session.getAttributes().get("userId").toString());
            String chatId = session.getAttributes().get("chat_id").toString();
            ChatHistoryEntity chatHistoryEntity = new ChatHistoryEntity();
            chatHistoryEntity.setChatId(chatId);
            chatHistoryEntity.setItemId(itemId);
            chatHistoryEntity.setType(type);
            chatHistoryEntity.setContent(content);
            chatHistoryEntity.setUserId(userId);
            chatHistoryEntity.setRoleId(Long.valueOf((String) session.getAttributes().get("role_id")));
            chatHistoryEntity.setUseContext(Boolean.TRUE);
            if (type.equals("prompt")) {
                chatHistoryEntity.setIcon("/images/avatar/user.png");
                chatHistoryEntity.setTokens(tokens);
            } else {
                chatHistoryEntity.setIcon("/images/avatar/gpt.png");
                // tokens 同个chatId做累加处理
                int sunTokens = chatHistoryService.getChatHistoryByUserId(userId, type, chatId).stream().map(ChatHistoryEntity::getTokens).
                        reduce(Integer::sum).orElse(0);
                chatHistoryEntity.setTokens(sunTokens + tokens);
            }
            chatHistoryService.save(chatHistoryEntity);
        }
    }

    public void sendMessage(String message) {
        ChatAiSocketHandler.sendMessage(session, message);
    }

    public void replyErrorMessage(String message) {
        ChatAiSocketHandler.replyErrorMessage(session, message);
    }
}
